package com.bl.file.service;

import com.bl.file.util.ServerIpUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import com.bl.file.config.NettyProperties;

/**
 * @author yangxiaodong
 * @version 1.0
 * @description: netty文件
 * @date 2025/7/2 14:00
 */
@Slf4j
@Component
public class NettyFileServer implements CommandLineRunner {

    @Resource
    private NettyProperties nettyProperties;

    private void startServer() {
        int port = nettyProperties.getServerPort();
        int cores = Runtime.getRuntime().availableProcessors();
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup(cores * 2);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new HttpServerCodec());
//                            p.addLast(new HttpContentDecompressor());
                            p.addLast(new ChunkedWriteHandler());
                            p.addLast(new StreamFileHandler(nettyProperties));
                        }
                    });

            ChannelFuture f = bootstrap.bind(port).sync();
            log.info("🚀 Netty File Server started at http://{}:{}", ServerIpUtils.getLocalIpAddress(), port);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }


    @Override
    public void run(String... args) throws Exception {
        startServer();
    }
}
